package com.gitee.sergius.apitool.parser.convertor.request;

import com.gitee.sergius.apitool.annotation.ApiModel;
import com.gitee.sergius.apitool.annotation.ApiParam;
import com.gitee.sergius.apitool.entity.RequestParamEntity;

import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shawn yang
 * @version 1.0.0
 * <p><pre>用于解析{@link ApiParam}标签定义的请求参数</pre>
 *
 */
public class ApiParamToEntityListConvertor {

    /**
     * 将方法参数上添加的{@link ApiParam}注释解析成实体类
     *
     * @param parameters 方法参数
     * @param requestParamEntityList 用来保存解析出来的入参数据
     */
    public static void parse(Parameter[] parameters, List<RequestParamEntity> requestParamEntityList) {
        if (parameters == null || parameters.length == 0) {
            return;
        }
        if (requestParamEntityList == null) {
            requestParamEntityList = new ArrayList<>();
        }

        for (Parameter param : parameters) {
            if (!param.isAnnotationPresent(ApiParam.class)) {
                continue;
            }
            requestParamEntityList.addAll(parseParamClazzToList(param));
        }

    }


    /**
     * @param param
     * @return
     */
    private static List<RequestParamEntity> parseParamClazzToList(Parameter param) {
        List<RequestParamEntity> requestParamEntityList = new ArrayList<>();

        Class paramClazz = param.getType();

        if (paramClazz.isAnnotationPresent(ApiModel.class)) {
            requestParamEntityList.addAll(RequestModelToEntityConvertor.parseModelToEntity(paramClazz,1));
        } else {

            ApiParam apiParam = param.getAnnotation(ApiParam.class);

            RequestParamEntity requestParamEntity = RequestNotModelToEntityConvertor.parseNotModelToEntity(paramClazz, param.getParameterizedType(), apiParam.name(), apiParam.desc(), apiParam.required(), apiParam.example(),1);

            requestParamEntityList.add(requestParamEntity);
        }

        return requestParamEntityList;
    }


}
